package com.cg.design.graphicdesignpattern.bridge;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * 类的实现层次结构：FileDisplayImpl类，实现显示文本内容功能
 *
 * @program: LeetCode->FileDisplayImpl
 * @description: 类的实现层次结构：FileDisplayImpl类，实现显示文本内容功能
 * @author: cg
 * @create: 2022-03-24 00:14
 **/
public class FileDisplayImpl extends DisplayImpl {

    /**
     * 文件名
     */
    private String fileName;
    /**
     * 读文件流
     */
    private BufferedReader reader;
    /**
     * 循环显示的极限(缓存大小限制)
     */
    private final int MAX_READAHEAD_LIMIT = 4096;

    public FileDisplayImpl(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void rawOpen() {
        try {
            reader = new BufferedReader(new FileReader(fileName));
            reader.mark(MAX_READAHEAD_LIMIT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("=-=-=-=-=-= " + fileName + " =-=-=-=-=-=");
    }

    @Override
    public void rawPrint() {
        try {
            String line;
            // 回到mark的位置
            reader.reset();
            while ((line = reader.readLine()) != null) {
                System.out.println("> " + line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void rawClose() {
        System.out.println("=-=-=-=-=-= ");
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
